<template>
  <view class="share-popup-wrapper">
    <!-- 自定义分享弹窗 -->
    <tn-popup
      mode="bottom"
      v-model="showPopup"
      :maskCloseable="true"
      :customStyle="{borderRadius: '30rpx 30rpx 0 0', overflow: 'hidden'}"
      backgroundColor="transparent"
      @close="handleClose"
    >
      <view class="share-popup">
        <!-- 弹窗头部 -->
        <view class="popup-header">
          <view class="header-title">分享到</view>
          <view class="close-btn" @tap="handleClose">
            <text class="tn-icon-close"></text>
          </view>
        </view>
        
        <!-- 分享选项 -->
        <view class="share-options">
          <!-- 微信好友分享 (小程序专用按钮) -->
          <view class="share-item wechat-item-animated">
            <button 
              class="share-btn wechat-btn wechat-btn-animated"
              open-type="share"
              @tap="handleWechatShare"
              :data-image="shareImage"
              :data-title="shareTitle"
            >
              <view class="share-icon wechat-icon">
                <text class="tn-icon-wechat-fill"></text>
              </view>
              <text class="share-name">微信好友</text>
            </button>
          </view>
          
          <!-- 保存到相册 -->
          <view class="share-item" @tap="handleSaveToAlbum">
            <view class="share-btn">
              <view class="share-icon save-icon">
                <text class="tn-icon-download"></text>
              </view>
              <text class="share-name">保存相册</text>
            </view>
          </view>
          
          <!-- 分享到朋友圈 (通过保存图片实现) -->
          <view class="share-item" @tap="handleShareMoments">
            <view class="share-btn">
              <view class="share-icon moments-icon">
                <text class="tn-icon-moments"></text>
              </view>
              <text class="share-name">朋友圈</text>
            </view>
          </view>
        </view>
        
        <!-- 取消按钮 -->
        <view class="cancel-section">
          <view class="cancel-btn" @tap="handleClose">
            取消
          </view>
        </view>
      </view>
    </tn-popup>
  </view>
</template>

<script>
export default {
  name: 'SharePopup',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    shareImage: {
      type: String,
      default: ''
    },
    shareTitle: {
      type: String,
      default: '我的美照制作'
    },
    shareDesc: {
      type: String,
      default: '快来看看我制作的美照吧～'
    }
  },
  data() {
    return {
      showPopup: false
    };
  },
  watch: {
    show: {
      handler(newVal) {
        this.showPopup = newVal;
      },
      immediate: true
    },
    showPopup(newVal) {
      if (!newVal) {
        this.$emit('update:show', false);
        this.$emit('close');
      }
    }
  },
  methods: {
    // 处理关闭弹窗
    handleClose() {
      this.showPopup = false;
    },
    
    // 微信好友分享 (小程序原生分享)
    handleWechatShare() {
      console.log('触发微信好友分享', {
        image: this.shareImage,
        title: this.shareTitle
      });
      
      // 微信小程序分享会自动触发 onShareAppMessage
      // 这里只需要关闭弹窗并通知父组件
      this.handleClose();
      this.$emit('share-success', {
        type: 'wechat',
        platform: '微信好友'
      });
    },
    
    // 保存到相册
    async handleSaveToAlbum() {
      if (!this.shareImage) {
        uni.showToast({
          title: '没有可保存的图片',
          icon: 'none'
        });
        return;
      }
      
      try {
        // 显示加载提示
        uni.showLoading({
          title: '保存中...'
        });
        
        // 下载图片
        const downloadRes = await this.downloadImage(this.shareImage);
        
        // 保存到相册
        await this.saveToAlbum(downloadRes.tempFilePath);
        
        uni.hideLoading();
        uni.showToast({
          title: '已保存到相册',
          icon: 'success'
        });
        
        this.handleClose();
        this.$emit('share-success', {
          type: 'save',
          platform: '本地相册'
        });
        
      } catch (error) {
        uni.hideLoading();
        console.error('保存图片失败:', error);
        
        if (error.errMsg && error.errMsg.includes('auth deny')) {
          uni.showModal({
            title: '需要授权',
            content: '需要授权访问相册才能保存图片，请在设置中开启相册权限',
            showCancel: false
          });
        } else {
          uni.showToast({
            title: '保存失败，请重试',
            icon: 'none'
          });
        }
      }
    },
    
    // 分享到朋友圈 (通过提示保存图片实现)
    handleShareMoments() {
      uni.showModal({
        title: '分享到朋友圈',
        content: '将为您保存图片到相册，然后您可以手动发布到朋友圈',
        confirmText: '保存图片',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.handleSaveToAlbum();
          }
        }
      });
    },
    
    // 下载图片 Promise 封装
    downloadImage(url) {
      return new Promise((resolve, reject) => {
        uni.downloadFile({
          url: url,
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(res);
            } else {
              reject(new Error('下载失败'));
            }
          },
          fail: reject
        });
      });
    },
    
    // 保存到相册 Promise 封装
    saveToAlbum(filePath) {
      return new Promise((resolve, reject) => {
        uni.saveImageToPhotosAlbum({
          filePath: filePath,
          success: resolve,
          fail: reject
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.share-popup-wrapper {
  .share-popup {
    background: #1a1a1a;
    border-radius: 30rpx 30rpx 0 0;
    padding-bottom: env(safe-area-inset-bottom);
    overflow: hidden;
    box-shadow: 0 -10rpx 40rpx rgba(0, 0, 0, 0.3);
  }
  
  .popup-header {
    position: relative;
    padding: 30rpx 40rpx 20rpx;
    border-bottom: 1px solid rgba(255, 255, 255, 0.03);
    
    .header-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #e0e0e0;
      text-align: center;
      width: 100%;
    }
    
    .close-btn {
      position: absolute;
      right: 40rpx;
      top: 50%;
      transform: translateY(-50%);
      width: 50rpx;
      height: 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.05);
      
      text {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.6);
      }
      
      &:active {
        background: rgba(255, 255, 255, 0.1);
      }
    }
  }
  
  .share-options {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 30rpx;
    padding: 40rpx;
    
    .share-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .share-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20rpx;
        border-radius: 20rpx;
        background: transparent;
        border: none;
        transition: all 0.2s ease;
        width: 100%;
        
        &:active {
          transform: scale(0.95);
          background: rgba(255, 255, 255, 0.05);
        }
        
        // 微信按钮特殊样式（去除默认样式）
        &.wechat-btn {
          background: transparent !important;
          border: none !important;
          padding: 20rpx !important;
          margin: 0 !important;
          font-size: inherit;
          line-height: inherit;
          color: inherit;
          
          &::after {
            border: none;
            background: none;
          }
        }
        
        .share-icon {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 15rpx;
          
          text {
            font-size: 40rpx;
          }
          
          &.wechat-icon {
            background: linear-gradient(135deg, #1aad19, #00d100);
            
            text {
              color: #ffffff;
            }
          }
          
          &.save-icon {
            background: linear-gradient(135deg, #007AFF, #5AC8FA);
            
            text {
              color: #ffffff;
            }
          }
          
          &.moments-icon {
            background: linear-gradient(135deg, #C7C7CC, #8E8E93);
            
            text {
              color: #ffffff;
            }
          }
        }
        
        .share-name {
          font-size: 24rpx;
          color: rgba(224, 224, 224, 0.8);
          text-align: center;
          line-height: 1.2;
        }
      }
    }
  }
  
  .cancel-section {
    padding: 0 40rpx 40rpx;
    
    .cancel-btn {
      width: 100%;
      height: 88rpx;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 44rpx;
      border: 1px solid rgba(255, 255, 255, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30rpx;
      color: rgba(224, 224, 224, 0.7);
      font-weight: 500;
      transition: all 0.2s ease;
      
      &:active {
        background: rgba(255, 255, 255, 0.08);
        transform: scale(0.98);
      }
    }
  }
}

// 微信好友分享按钮动画
.wechat-item-animated {
  .share-btn.wechat-btn-animated {
    .share-icon.wechat-icon {
      animation: wechatIconPulse 1.8s infinite;
    }

    .share-name {
      animation: wechatTextGlow 1.8s infinite;
    }
  }
}

@keyframes wechatIconPulse {
  0%, 100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(26, 173, 25, 0.5);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 0 0 8rpx rgba(26, 173, 25, 0.1);
  }
}

@keyframes wechatTextGlow {
  0%, 100% {
    color: rgba(224, 224, 224, 0.8);
  }
  50% {
    color: #1aad19;
    text-shadow: 0 0 8rpx rgba(26, 173, 25, 0.3);
  }
}

// 响应式设计
@media screen and (max-width: 400px) {
  .share-popup-wrapper {
    .share-options {
      gap: 20rpx;
      padding: 30rpx;
      
      .share-item .share-btn {
        padding: 15rpx;
        
        .share-icon {
          width: 70rpx;
          height: 70rpx;
          margin-bottom: 12rpx;
          
          text {
            font-size: 36rpx;
          }
        }
        
        .share-name {
          font-size: 22rpx;
        }
      }
    }
    
    .cancel-section {
      padding: 0 30rpx 30rpx;
      
      .cancel-btn {
        height: 78rpx;
        font-size: 28rpx;
      }
    }
  }
}
</style>
